"""
Webhook API路由
"""

from fastapi import APIRouter, HTTPException, Request, Header
from typing import Dict, Any, Optional

from managers.stripe_manager import StripeManager

router = APIRouter(tags=["Webhook管理"])

# 创建全局的Stripe管理器实例
stripe_manager = StripeManager()


@router.post("/webhook")
async def handle_webhook(
    request: Request,
    stripe_signature: Optional[str] = Header(None)
):
    """处理Stripe webhook事件"""
    if not stripe_signature:
        raise HTTPException(status_code=400, detail="缺少Stripe签名")
    
    return await stripe_manager.webhook_service.process_webhook(request, stripe_signature)


@router.get("/api/webhook/events")
async def get_supported_events():
    """获取支持的事件类型列表"""
    return {
        "supported_events": stripe_manager.webhook_service.get_supported_events(),
        "total_count": len(stripe_manager.webhook_service.event_handlers)
    }


@router.get("/api/webhook/handlers")
async def get_handler_info():
    """获取所有事件处理器的信息"""
    return {
        "handlers": stripe_manager.webhook_service.get_handler_info(),
        "total_count": len(stripe_manager.webhook_service.event_handlers)
    }


@router.post("/api/webhook/test")
async def test_webhook():
    """测试webhook端点"""
    return {
        "status": "success",
        "message": "Webhook端点正常工作",
        "webhook_url": stripe_manager.webhook_service.endpoint_secret[:10] + "...",
        "supported_events_count": len(stripe_manager.webhook_service.event_handlers)
    }


@router.post("/api/webhook/add-handler")
async def add_custom_handler(event_type: str, handler_name: str):
    """添加自定义事件处理器（示例）"""
    try:
        # 这里只是一个示例，实际使用时需要更复杂的逻辑
        def custom_handler(event_data):
            return {"custom_handler": handler_name, "event_type": event_type}
        
        stripe_manager.webhook_service.add_custom_handler(event_type, custom_handler)
        
        return {
            "status": "success",
            "message": f"自定义处理器 {handler_name} 已添加到事件 {event_type}",
            "event_type": event_type,
            "handler_name": handler_name
        }
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"添加处理器失败: {str(e)}")


@router.delete("/api/webhook/remove-handler/{event_type}")
async def remove_handler(event_type: str):
    """移除事件处理器"""
    try:
        stripe_manager.webhook_service.remove_handler(event_type)
        
        return {
            "status": "success",
            "message": f"事件处理器 {event_type} 已移除",
            "event_type": event_type
        }
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"移除处理器失败: {str(e)}")


@router.get("/api/webhook/status")
async def get_webhook_status():
    """获取webhook状态信息"""
    return {
        "webhook_url": stripe_manager.webhook_service.endpoint_secret[:10] + "...",
        "supported_events": stripe_manager.webhook_service.get_supported_events(),
        "handler_count": len(stripe_manager.webhook_service.event_handlers),
        "handlers": stripe_manager.webhook_service.get_handler_info()
    }
